/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021. All rights reserved.
 */

package org.opengauss.driver;


import java.util.Enumeration;
import java.util.Properties;

/**
 * description:this for AbstraceDriverInfo Class
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2021.
 *
 * @author Administrator
 * @version [openGauss_debug 0.0.1 2021/4/23]
 * @since 2021/4/23
 */
public abstract class AbstraceDriverInfo implements IDriverInfo {
    protected Properties jdbcProp;
    protected Properties urlProp;

    public AbstraceDriverInfo(Properties jdbcProp, Properties urlProp) {
        this.jdbcProp = jdbcProp;
        this.urlProp = urlProp;
    }

    protected abstract String getDriverPrefix();

    @Override
    public void addJdbcProperties(String key, String value) {
        this.jdbcProp.put(key, value);
    }
    
    @Override
    public void addProperties(String key, String value) {
        this.urlProp.put(key, value);
    }
    
    @Override
    public IDriverInfo clone() throws CloneNotSupportedException {
        AbstraceDriverInfo info = (AbstraceDriverInfo) super.clone();
        info.jdbcProp = (Properties) this.jdbcProp.clone();
        info.urlProp = (Properties) this.urlProp.clone();
        return info;
    }
    
    @Override
    public Properties getProperties() {
        Properties prop = (Properties) this.jdbcProp.clone();
        prop.put("url", getFormatConnectionInfo());
        prop.put("passwd", getPassword());
        prop.put("driver", getDriver());
        return prop;
    }

    @Override
    public String getUser() {
        return getKey("user");
    }

    @Override
    public String getPassword() {
        return getKey("password");
    }

    @Override
    public String getDatabase() {
        return getKey("database");
    }

    @Override
    public String getHosts() {
        return getKey("hosts");
    }

    @Override
    public String getFormatConnectionInfo() {
        StringBuilder sb = new StringBuilder(128);
        sb.append(getDriverPrefix());
        if (urlProp.size() > 0) {
            sb.append("?");
            sb.append(appendUrlParams());
        }
        return sb.toString();
    }

    protected String appendUrlParams() {
        StringBuilder sb = new StringBuilder(128);
        Enumeration<?> names = urlProp.propertyNames();
        while (names.hasMoreElements()) {
            String key = names.nextElement().toString();
            sb.append(key);
            sb.append("=");
            sb.append(this.urlProp.getProperty(key));
            sb.append("&");
        }
        return sb.substring(0, sb.length() - 1);
    }

    protected String getKey(String key) {
        return this.jdbcProp.getProperty(key);
    }
}
